package com.carlinfo.controller.back;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.carlinfo.common.controller.BaseController;
import com.carlinfo.common.util.ConstantFinalUtil;
import com.carlinfo.common.util.EncryptUtil;
import com.carlinfo.users.pojo.AAdmin;
import com.carlinfo.users.service.IAdminService;

/**
 * 
 * @author Gonsen
 * 后台管理
 */
@Controller
@RequestMapping("/admin")
public class AdminHeadController extends BaseController {

	@Resource
	IAdminService adminService;

	/**
	 * 后台登录页面
	 * @param session
	 * @return "/back/login"
	 */
	@RequestMapping("/login")
	public String login(HttpSession session) {
		ConstantFinalUtil.LOGGER.info("==== admin login ====");
		AAdmin admin= (AAdmin)session.getAttribute("admin");
		if(admin!=null) {
			return "redirect:/back/index.htm";
		}
		return "/back/login";
	}
	
	/**
	 * 摧毁session回话返回登录页面
	 * @param session
	 * @return back/login.htm
	 */
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		ConstantFinalUtil.LOGGER.info("==== admin logout ====");
		session.invalidate();
		return "redirect:/back/login.htm";
	}
	
	/**
	 * 登录验证
	 * @param model
	 * @param session
	 * @param email
	 * @param password
	 * @param code
	 * @return  back/login
	 */
	@RequestMapping("/loginSubmit")
	public String loginSubmit(Model model, HttpSession session, String email, String password, String code) {
		ConstantFinalUtil.LOGGER.info("==== admin loginSubmit ====");
		String respMsg = "";
		String sessionCode = session.getAttribute("rand").toString();
		System.out.println("sessionCode= " + sessionCode);
		System.out.println("code= " + code);
		/* 判断验证码 */
		if (!sessionCode.equalsIgnoreCase(code)) {
			respMsg = "验证码不正确";
		} else {
			/* 查找邮箱是否存在 */
			Map<String, Object> conMap = new HashMap<>();
			conMap.put("email", email);
			AAdmin admin = adminService.findOneAdminSercice(conMap);
			if (admin == null) {
				respMsg = "邮箱不存在";
			} else {
				/* 判断账户状态 */
				if (admin.getStatus() == 0) {
					respMsg = "账户被禁用";
				} else {
					/* 判断密码是否正确 */
					System.out.println(EncryptUtil.sha256EncodeStr(password));
					System.out.println(admin.getPassword());
					System.out.println(admin.getPassword().equals(EncryptUtil.sha256EncodeStr(password)));
					if (EncryptUtil.sha256CheckStr(password, admin.getPassword())) {
						session.setAttribute("admin", admin);
						return "redirect:/back/index.htm";
					}else {
						respMsg = "密码不正确";
					}
				}
			}
		}
		model.addAttribute("respMsg", respMsg);
		return "/back/login";
	}
	
}
